package com.stark.commons.spring.web.support.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;

/**
 * {@link BindExceptionHandler} 异常处理器。
 * <p>返回 <code>400</code>状态码及错误信息。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
public class BindExceptionHandler implements ExceptionHandler {
	
	@Override
	public boolean instanceofException(Exception ex) {
		return ex instanceof BindException;
	}

	@Override
	public ResponseEntity<String> handle(Exception ex) {
		String errmsg = ((BindException) ex).getBindingResult().getFieldErrors()
				.stream()
				.map(e -> e.getField() + ":" + e.getDefaultMessage())
				.reduce("", (str1, str2) -> str1 + ("".equals(str1) ? "" : "\n") + str2);
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errmsg);
	}

}
